/**
 * Created by zl on 2017/4/12.
 */

'use strict';
const router = require('express').Router();
const config = require("../../config");
const companyService = require("../service/company");
const formidable = require('formidable');
const fs = require('fs');
const nodeExcel = require('excel-export');
const moment = require('moment');
const path = require('path');


/**
 * 获取价格表
 */
router.get('/pricetable', function (req, res) {
    companyService.getPriceTablle().then((result) => {
        res.json({
            success: true,
            data:result
        });
    },(err) => {
        console.info(err);
        res.json({
            success: false
        });
    })

})



/**
 * 提交信息
 * name: 企业名称
 * address: 企业地址
 * num: 员工人数
 * contact: 联系人
 * tel: 联系电话
 * advance: 擅长维修项目
 * liscene: 营业执照
 */
router.post("/submit", function (req, res) {
    var form = new formidable.IncomingForm();   //创建上传表单
    form.encoding = 'utf-8';        //设置编辑
    form.uploadDir = './public/liscene/';     //设置上传目录 文件会自动保存在这里
    form.keepExtensions = true;     //保留后缀
    form.maxFieldsSize = 5 * 1024 * 1024 ;   //文件大小5M

    form.parse(req, function (err, fields, files) {
        if (err) {
            console.info(err);
            res.json({
                success: false
            });
            return;
        }
        let data = {
            name: fields.name,
            address: fields.address,
            advance: fields.advance,
            contact: fields.contact,
            num: fields.num,
            tel: fields.tel,
            liscene: files.liscene.path.substring(7,files.liscene.path.length)
        };
        companyService.saveCompany(data).then((result) => {
            res.json({
                success: true
            });
        },(err) => {
            console.info(err);
            res.json({
                success: false
            });
        })
    });
});

router.get('/download', function (req, res) {
    res.render('views/download.html');
})


router.post('/export', function (req, res) {
    var token = req.body.token;
    if(token != "sYHiwe4hvh9vuq9v3vGH56PUHR33") {
        res.json({
            success:false
        });
        return;
    }

    var excelData = [];
    companyService.getall().then((result) => {
        result.forEach(function (item) {
            var user = [];
            user.push(item.name);
            user.push(item.address);
            user.push(item.num.toString());
            user.push(item.contact);
            user.push(item.tel);
            user.push(item.advance);
            user.push(config.baseUrl + item.liscene);
            user.push(moment(item.create_time).format("YYYY-MM-DD HH:mm:ss"));
            excelData.push(user);
        });

        getExcel(excelData, function (err, buffer) {
            var fileName = "attachment;filename=company_info.xlsx";
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", fileName);
            res.end(buffer, 'binary');
        });


    },(err) => {
        console.info(err);
        res.json({
            success: false
        });
    })

});


function getExcel(data, callback) {
    var conf = {};
    conf.cols = [
        {caption: '企业名称', type: 'string'},
        {caption: '企业地址', type: 'string'},
        {caption: '员工人数', type: 'string'},
        {caption: '联系人', type: 'string'},
        {caption: '联系电话', type: 'string'},
        {caption: '擅长维修项目', type: 'string'},
        {caption: '营业执照', type: 'string'},
        {caption: '提交时间', type: 'string'},
    ];
    conf.rows = data;
    var result = nodeExcel.execute(conf);
    callback(null, result);
}


module.exports = router;